/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main_com.Controlers.file;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import main_com.mapper.FileMapper;
import main_com.pojo.FileBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;


@Controller
@RequestMapping("/FileUpController")
public class FileUpController {

    @Autowired
    FileMapper fileMapper;

    @RequestMapping("/fileUp")
    protected void fileUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Part file = request.getPart("file");
            String userName = request.getServletContext().getAttribute("userName").toString();
            String fileName = file.getSubmittedFileName();
            if (fileMapper.findFileCountByUserNameAndFileName(userName, fileName) > 0) {
                response.sendRedirect("http://localhost/fileManager/fileUp.jsp");
                return;
            }
            String path = "src/main/webapp/files/" + userName;
            File dir = new File(path);
            String filePath = path + "/" + fileName;
            if (!dir.exists()) {
                System.out.println(dir.mkdirs());
            }
            OutputStream os = new FileOutputStream(filePath);
            InputStream is = file.getInputStream();
            byte[] buffer = new byte[1024];
            int l = is.read(buffer);
            while (l != -1) {
                os.write(buffer, 0, l);
                l = is.read(buffer);
            }
            is.close();
            os.close();
            String contentType = fileName.substring(fileName.lastIndexOf(".") + 1) + "文件";
            String title = request.getParameter("title");
            String size = String.valueOf(file.getSize());
            filePath = "http://localhost/files/" + userName + "/" + fileName;
            fileMapper.addFile(new FileBean(userName, title, fileName, contentType, size, filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.sendRedirect("http://localhost/FileDownController/fileDown");
    }

}
